//
//  RACExampleVC.m
//  RACLearning
//
//  Created by 李阳 on 2018/6/11.
//  Copyright © 2018年 李阳. All rights reserved.
//

#import "RACExampleVC.h"
#import "ReactiveCocoa.h"
#import <UIView+YYAdd.h>

#import "UIApplication+RACSignalSupport.h"

@interface RACExampleVC ()

/// 输入框
@property (nonatomic, weak) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *obtainAuthCodeButton;
@property (weak, nonatomic) IBOutlet UITextField *authCodeTextField;

@end

@implementation RACExampleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupPipeline];
    
    [self setupAuthCodePipeline];
}


- (void)setupTakeScreenshotPipeline
{
    /*
    UIApplication *app = [UIApplication sharedApplication];
    
    //1
    RACSignal *isNotActive = [app.willResignActiveSignal
                              map:^id(NSNotification *notification) {
                                  return [NSNumber numberWithBool:NO];
                              }];
    
    RACSignal *isActive = [[[app.didBecomeActiveSignal
                             map:^id(NSNotification *notification) {
                                 return [NSNumber numberWithBool:YES];
                             }]
                            startWith:[NSNumber numberWithBool:YES]]
                           merge:isNotActive];
    
    RACSignal *isNotInBackground = [app.didEnterBackgroundSignal
                                    map:^id(NSNotification *notification) {
                                        return [NSNumber numberWithBool:NO];
                                    }];
    
    RACSignal *isInForeground = [[[app.willEnterForegroundSignal
                                   map:^id(NSNotification *notification) {
                                       return [NSNumber numberWithBool:YES];
                                   }]
                                  startWith:[NSNumber numberWithBool:YES]]
                                 merge:isNotInBackground];
    
    //2
    RACSignal *didTakeScreenshot = app.userDidTakeScreenshotSignal;
    
    @weakify(self);
    RACSignal *imageSignal = [[[[[[[RACSignal if:[RACSignal merge:@[isInForeground, isActive]] then:didTakeScreenshot else:[RACSignal never]] //3
                                   takeUntil:self.rac_willDeallocSignal]
                                  filter:^BOOL(id value) {
                                      //4
                                      @strongify(self);
                                      return [self filterScreenshotNotification];
                                  }]
                                 filter:^BOOL(id value) {
                                     //5
                                     @strongify(self);
                                     return self.previewShotView == nil;
                                 }]
                                map:^id(NSNotification *notification) {
                                    //6
                                    @strongify(self);
                                    return [self takeCurrentScreenshotOfWebview];
                                }]
                               multicast:[RACReplaySubject subject]]
                              autoconnect];//7
    
    //8
    RACSignal *hotSignalForPreview = [[[imageSignal
                                        map:^id(UIImage *image) {
                                            @strongify(self);
                                            return [self showScreenshotPreviewView:image];
                                        }]
                                       multicast:[RACReplaySubject subject]]
                                      autoconnect];
    
    //9
    RACSignal *cancel = [[hotSignalForPreview
                          map:^id(FMScreenshotPreviewView *previewView) {
                              return [previewView.cancelSignal
                                      map:^id(id value) {
                                          return nil;
                                      }];
                          }]
                         switchToLatest];
    
    //10
    RACSignal *editImage = [[hotSignalForPreview
                             map:^id(FMScreenshotPreviewView *previewView) {
                                 return [previewView.editImage
                                         map:^id(id value) {
                                             return nil;
                                         }];
                             }]
                            switchToLatest];
    
    //11
    RACSignal *otherActionForHidePreview = [[hotSignalForPreview
                                             map:^id(id value) {
                                                 RACSignal *willResignActive = [[[NSNotificationCenter.defaultCenter rac_addObserverForName:UIApplicationWillResignActiveNotification object:nil]
                                                                                 take:1]
                                                                                takeUntil:[RACSignal merge:@[cancel, editImage]]];
                                                 
                                                 RACSignal *timeout = [[[RACSignal return:nil]
                                                                        delay:10.0]
                                                                       takeUntil:[RACSignal merge:@[cancel, editImage, willResignActive]]];
                                                 
                                                 
                                                 return [[RACSignal merge:@[timeout, willResignActive]]
                                                         take:1];
                                             }]
                                            switchToLatest];
    
    //12
    RACSignal *shouldHidePreviewView = [RACSignal merge:@[cancel, editImage, otherActionForHidePreview]];
    
    //13
    RACSignal *viewWillDisappear = [self rac_signalForSelector:@selector(viewWillDisappear:)];
    
    //14
    [[[shouldHidePreviewView
       zipWith:hotSignalForPreview]
      takeUntil:viewWillDisappear]//13
     subscribeNext:^(RACTuple *tuple) {
         @strongify(self);
         [self hideScreenshotPreviewView:tuple];
     } completed:^{
     }];
    
    //15
    [[[imageSignal sample:editImage]
      takeUntil:viewWillDisappear]
     subscribeNext:^(UIImage *image) {
         @strongify(self);
         [self showDrawViewController:image];
     } completed:^{
     }];
     */
}


- (void)setupAuthCodePipeline
{
    @weakify(self);
    [[[[[self.obtainAuthCodeButton rac_signalForControlEvents:UIControlEventTouchUpInside] map:^id(id value) {
        @strongify(self);
        return [self tipsAndEnableSignalWhileObtainAuthCode];
    }]  switchToLatest] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(RACTuple *tuple) {
        
        @strongify(self);
        
        NSString *title = tuple.first;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.obtainAuthCodeButton setTitle:title forState:UIControlStateNormal];
            
            self.obtainAuthCodeButton.enabled = [tuple.second boolValue];
        });
        
    } completed:^{
        NSLog(@"%s, pipeline auth code completed", __PRETTY_FUNCTION__);
    }] ;
}
- (void)setupPipeline
{
    @weakify(self);
    RACSignal *keyboardWillShowSignal = [[NSNotificationCenter.defaultCenter rac_addObserverForName:UIKeyboardWillShowNotification object:nil] map:^id(NSNotification *notify) {
        return notify.userInfo[UIKeyboardFrameEndUserInfoKey];
    }];
    
    [[[[[NSNotificationCenter.defaultCenter rac_addObserverForName:UIKeyboardWillHideNotification object:nil] map:^id(NSNotification *notify) {
        return [NSValue valueWithCGRect:CGRectZero];
    }] merge:keyboardWillShowSignal] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSValue *value) {
        NSLog(@"keyboard size is: %@", value);
        
        CGRect rect = value.CGRectValue;
        
        CGFloat height = rect.size.height;
        
        @strongify(self);
        
        [UIView animateWithDuration:0.25 animations:^{
            if (height == 0)
            {
                self.textField.transform = CGAffineTransformIdentity;
            }
            else
            {
                CGFloat totalH = self.view.height;
                CGFloat deltaY = self.textField.bottom - (totalH - height) + 5;
                self.textField.transform = CGAffineTransformMakeTranslation(0, -deltaY);
            }
        }];
        
    } completed:^{
       NSLog(@"%s, Keyboard Notification signal completed", __PRETTY_FUNCTION__);
    }];
}

- (RACSignal *)tipsAndEnableSignalWhileObtainAuthCode
{
    static const NSInteger n = 60;
    
    RACSignal *timer = [[[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] map:^id(id value) {
        return nil;
    }] startWith:nil];
    
    NSMutableArray *numbers = [NSMutableArray array];
    for (NSInteger i = n; i>= 0; i--)
    {
        [numbers addObject:@(i)];
    }
    
    return [[[[[numbers.rac_sequence.signal zipWith:timer] map:^id(RACTuple *tuple) {
        NSInteger count = [tuple.first integerValue];
        if (count == 0)
        {
            return RACTuplePack(@"重试", @(YES));
        }
        else
        {
            NSString *title = [NSString stringWithFormat:@"重试(%lds)", count];
            return RACTuplePack(title, @(NO));
        }
    }] takeUntil:self.rac_willDeallocSignal]  setNameWithFormat:@"%s tips and enable signal while obtain auth code", __PRETTY_FUNCTION__] logCompleted];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
